package com.hwn.datax.controller;

import cn.hutool.json.JSONUtil;
import com.hwn.datax.service.ConfigService;
import com.hwn.datax.utils.AlertUtil;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextArea;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

/**
 * @author wnhuang
 * @date 2024/6/2 1:08
 */
@Controller
public class ConfigController {


    @FXML
    public ComboBox<String> keyComboBox;

    @FXML
    public TextArea valueTextArea;

    ObservableList<String> keyItems = FXCollections.observableArrayList();

    @Autowired
    ConfigService configService;

    public void initialize() {
        keyComboBox.setItems(keyItems);
        keyItems.clear();
        keyItems.add("全部");
        keyItems.addAll(configService.getAllConfig().keySet());
        keyComboBox.setOnAction(event -> {
            String key = keyComboBox.getValue();
            String jsonValue;
            if ("全部".equals(key)) {
                jsonValue = JSONUtil.toJsonStr(configService.getAllConfig(), 4);
            } else {
                jsonValue = JSONUtil.toJsonStr(configService.getConfig(key), 4);
            }
            valueTextArea.setText(jsonValue);
        });
    }

    public void onSave(ActionEvent actionEvent) {
        String key = keyComboBox.getValue();
        String value = valueTextArea.getText();
        if ("全部".equals(key)) {
            configService.saveAllConfig(value);
        } else {
            configService.saveConfig(key, value);
        }
        AlertUtil.showSuccessAlert("保存成功！");
    }
}
